/**
 * @description  流程查询
 * @author shenhong
 */
import React, { PropTypes, PureComponent, Fragment } from 'react';
import { connect, routerRedux } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tooltip, message } from 'antd';
import { ContentPackage, TableC, DATA_ENTRY, AdvancedSearch, ModalC, FormGroup } from '../../../comps';
import moment from 'moment';
import _ from 'lodash';
import style from './index.less';

const FormItem = Form.Item;
@Form.create()
class LiquidityRisk extends PureComponent {
  constructor() {
    super();
    this.state = {
      formData: {},
      currentUser: {}, // 用户信息
      currentPage: 1,
      numInPage: 20,
      isReset: false,
      isUser: false,
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      // 获取所有用户数据
      type: 'processQueryM/getApplyPeople',
      payload: {},
    });
    const {
      globalM: {
        dataDictionary: { flow = [], FLOWSTATE = [] },
      },
    } = this.props;
    dispatch({
      // 获取字典
      type: 'processQueryM/save',
      payload: {
        selectData: {
          flow,
          flowstate: FLOWSTATE,
        },
      },
    });
    dispatch({
      // 获取当前用户信息
      type: 'processQueryM/getUserInfo',
      payload: localStorage.getItem('antd-pro-userId'),
      callback: (res) => {
        this.setState({
          currentUser: res,
        });
      },
    });
    dispatch({
      type: 'processQueryM/getTableData',
      payload: {},
    });
  }

  // 点击审批
  approvelData = (record) => {
    const { currentUser } = this.state;
    const task = record.aboutMeTasks;
    let taskId = '';
    task.map((item) => {
      if ((item.userId = currentUser.userId)) {
        taskId = item.id;
      }
    });
    const query = {
      taskId: taskId,
      businessKey: record.businessKey,
      processInstanceId: record.id,
      startUser: record.startUser,
      type: record.flowType,
      starterNode: this.getstarterNode(record.aboutMeTasks),
    };
    sessionStorage.setItem('process', JSON.stringify(query));
    this.props.dispatch(routerRedux.push(`/agencyTask/autoPool`));
  };

  seeData = (record) => {
    const query = {
      taskId: record.taskId,
      businessKey: record.businessKey,
      processInstanceId: record.id,
      noOperate: true, // 是否展示按钮合审批意见输入框
      type: record.flowType,
    };
    sessionStorage.setItem('process', JSON.stringify(query));
    this.props.dispatch(routerRedux.push(`/agencyTask/autoPool`));
  };

  // 调单
  turnOver = (record) => {
    this.setState({
      turnOverRecord: record,
      turnOverShow: true,
      selectCurrentUser: record?.aboutMeTasks?.length == 1 ? record?.aboutMeTasks[0]?.userId : undefined,
    });
    if (record?.aboutMeTasks?.length == 1) {
      this.getOrderToUser(record?.aboutMeTasks[0]?.userId);
    }
  };
  // 查询调单人
  getOrderToUser = (userId) => {
    this.setState({
      selectCurrentUser: userId || undefined,
    });
    if (!userId) {
      return;
    }
    this.props.dispatch({
      type: 'processQueryM/getStationUserByUserId',
      payload: {
        userId,
      },
      callback: (_data) => {
        this.setState({
          targetUserList: _data,
        });
      },
    });
  };
  // 调单模态框
  turnOverModal = () => {
    const { turnOverShow, turnOverRecord, targetUserList = [], selectCurrentUser } = this.state;
    const { turnOverLoading, form } = this.props;
    const formProps = {
      onRef: (ref) => (this.formRef = ref),
      form: form,
      autoLayout: false,
      rowNumber: 1,
      dataSource: [
        {
          dataIndex: 'currentApprover1',
          title: '当前审批人',
          type: DATA_ENTRY.SELECT,
          positionBody: true,
          initialValue: turnOverRecord?.aboutMeTasks?.length == 1 ? turnOverRecord?.aboutMeTasks[0]?.userId : undefined,
          dataSource: (turnOverRecord?.aboutMeTasks || []).map((item) => {
            return { title: item.userName, value: item.userId };
          }),
          allowClear: true,
          disabled: turnOverRecord?.aboutMeTasks?.length == 1,
          rules: [{ required: true, message: '请选择当前审批人' }],
          onChange: this.getOrderToUser,
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
        },
        {
          dataIndex: 'orderToUser',
          title: '调单至',
          type: DATA_ENTRY.SELECT,
          positionBody: true,
          dataSource: targetUserList,
          allowClear: true,
          disabled: !selectCurrentUser,
          rules: [{ required: true, message: '请选择调单至人员' }],
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
        },
      ],
    };
    const modalProps = {
      title: '调单',
      width: 400,
      visible: turnOverShow,
      loading: turnOverLoading,
      onOk: this.turnOverOrder,
      onCancel: () => {
        this.setState({
          turnOverRecord: '',
          turnOverShow: false,
        });
      },
      maskClosable: false,
      destroyOnClose: true,
      children: <FormGroup {...formProps} />,
    };
    return <ModalC {...modalProps} />;
  };
  // 调单确认
  turnOverOrder = () => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    validateFields(['currentApprover1', 'orderToUser'], (err, values) => {
      if (!err) {
        if (values.currentApprover1 && values.orderToUser) {
          dispatch({
            type: 'processQueryM/turnOverOrder',
            payload: {
              currentApprover: values.currentApprover1,
              orderToUser: values.orderToUser,
            },
            callback: (msg) => {
              if (msg === 'success') {
                this.setState(
                  {
                    turnOverShow: false,
                    turnOverRecord: '',
                  },
                  () => {
                    this.searchData();
                  },
                );
              }
            },
          });
        }
      }
    });
  };
  // 获取是否是起始节点
  getstarterNode = (arr) => {
    const { currentUser } = this.state;
    const data = arr;
    let flag = undefined;
    if (data && data.length) {
      data.map((item) => {
        if (item.userId == currentUser.userId) {
          flag = item.starterNode;
        }
      });
    }
    return flag;
  };

  // 判断是否能审批
  showApprove = (arr) => {
    const { currentUser } = this.state;
    const userId = currentUser.userId;
    let flag = false;
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.userId == userId) {
          flag = true;
        }
      });
    }
    return flag;
  };

  // 拼接下一审批人
  changeText = (texts, record) => {
    const aboutMeTasks = record.aboutMeTasks || [];
    const tetArr = [];
    if (aboutMeTasks && aboutMeTasks.length) {
      aboutMeTasks.map((item) => {
        tetArr.push(item.userName);
      });
    }
    const text = _.join(tetArr, ',');
    return <span title={text}>{text}</span>;
  };

  // 改变coilumns的渲染样式
  changeColumns = (columns) => {
    const { isUser } = this.state;
    let newColumns = _.cloneDeep(columns);
    if (newColumns && newColumns.length) {
      if (newColumns[newColumns.length - 1].title !== '操作') {
        newColumns.push({
          title: '操作',
          dataIndex: 'id',
          key: 'id',
          render: (text, record) => {
            return (
              <Fragment>
                {this.showApprove(record.aboutMeTasks) ? (
                  <Tooltip title='审批'>
                    <a onClick={() => this.approvelData(record)}>审批</a>
                  </Tooltip>
                ) : null}
                {/* {!this.showApprove(record.aboutMeTasks)? null : <Divider type="vertical" />} */}
                {record?.aboutMeTasks?.length && localStorage.getItem('antd-pro-admin') == 'true' ? (
                  <Tooltip title='调单'>
                    <a onClick={() => this.turnOver(record)}>调单</a>
                  </Tooltip>
                ) : null}
                <Tooltip title='详情'>
                  <a onClick={() => this.seeData(record)}>详情</a>
                </Tooltip>
              </Fragment>
            );
          },
        });
      }
      newColumns.map((item) => {
        if (item.key == 'nextUser' || item.key == 'name' || item.key == 'flowChildType') {
          item.onCell = () => {
            return {
              style: {
                maxWidth: 150,
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            };
          };
          if (item.key == 'nextUser') {
            item.render = (text, record) => {
              return this.changeText(text, record);
            };
          } else {
            item.render = (text) => <span title={text}>{text}</span>;
          }
        }
      });
    }
    return newColumns;
  };

  // 分页信息
  handleChange = (pagination, sorter) => {
    const { isReset } = this.state;
    const { current, pageSize } = pagination;
    if (isReset) {
      message.warning('已重置查询条件，请重新输入查询条件查询');
      return;
    }
    const { formData } = this.state;
    const { dispatch } = this.props;
    const query = _.cloneDeep(formData);
    query.currentPage = current;
    query.numInPage = pageSize;
    dispatch({
      type: 'processQueryM/getTableData',
      payload: query,
    });
    // this.setState({
    //   currentPage:page,
    //   numInPage:pageSize
    // })
  };

  showTable = () => {
    const {
      processQueryM: { tableData },
      loading,
    } = this.props;
    const columns = tableData.columns;
    const newColumns = this.changeColumns(columns);
    const pageInfo = tableData.pageInfo;
    const dataSource = tableData.dataSource;
    return (
      <div>
        <TableC
          dataSource={dataSource}
          columns={newColumns}
          loading={loading}
          current={pageInfo && pageInfo.currentPage}
          total={pageInfo && pageInfo.total}
          pageSize={pageInfo && pageInfo.numInPage}
          onChange={this.handleChange}
          rowKey='id'
          selfScrollY={true}
        />
      </div>
    );
  };

  // 查询
  searchData = () => {
    const { formData } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'processQueryM/getTableData',
      payload: formData,
    });
  };

  // 转换流程申请人数据格式
  changeApply = (arry) => {
    let datas = [];
    if (arry && arry.length) {
      arry.map((item) => {
        datas.push({
          title: item.name,
          value: item.userId,
        });
      });
    }
    return datas;
  };

  // 更该审批状态值的格式
  changeType = (arr) => {
    const data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({
          title: item.value,
          value: item.value,
        });
      });
    }
    return data;
  };
  // 更该流程分类值的格式
  changeTypeTwo = (arr) => {
    const data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({
          title: item.value,
          value: item.code,
        });
      });
    }
    return data;
  };

  render() {
    const {
      processQueryM: { applyData, selectData },
    } = this.props;
    const people = this.changeApply(applyData);
    const processType = this.changeTypeTwo(selectData.flow);
    const flowState = this.changeType(selectData.flowstate);
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'flowType',
          title: '流程分类',
          type: DATA_ENTRY.SELECT,
          isMultiple: true,
          allowClear: true,
          dataSource: processType,
        },
        {
          dataIndex: ['startDate', 'endDate'],
          title: '日期区间',
          type: DATA_ENTRY.RANGEDATE,
          disableFuture: false,
        },
        {
          dataIndex: 'taskName',
          title: '任务名称',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'authStatus',
          title: '审批状态',
          type: DATA_ENTRY.SELECT,
          dataSource: flowState,
          allowClear: true,
        },
        {
          dataIndex: 'startUser',
          title: '发起人',
          type: DATA_ENTRY.SELECT,
          dataSource: people,
          allowClear: true,
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
        },
        {
          dataIndex: 'currentApprover',
          title: '当前审批人',
          type: DATA_ENTRY.SELECT,
          dataSource: people,
          allowClear: true,
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
        },
      ],
      onQuery: (e) => {
        const data = e;
        if (e.startDate) {
          data.startDate = e.startDate.format('YYYYMMDD');
        }
        if (e.endDate) {
          data.endDate = e.endDate.format('YYYYMMDD');
        }
        this.setState({ formData: data, isReset: false }, () => this.searchData(data));
      },
      onClear: () => {
        const { form } = this.props;
        form.resetFields();
        this.setState({
          isReset: true,
        });
      },
    };
    return (
      <ContentPackage
        title='流程查询'
        contentHtml={
          <div className={style.body_area}>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            <div style={{ marginTop: '10px' }}>{this.showTable()}</div>
            {this.turnOverModal()}
          </div>
        }
      />
    );
  }
}
export default connect(({ processQueryM, loading, globalM }) => ({
  processQueryM,
  loading: loading.effects['processQueryM/getTableData'],
  turnOverLoading: loading.effects['processQueryM/turnOverOrder'],
  globalM,
}))(LiquidityRisk);
